package com.qjj.studydainty.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.qjj.studydainty.R;
import com.qjj.studydainty.adapter.FileInfoAdapter;
import com.qjj.studydainty.entity.MyApplication;
import com.qjj.studydainty.entity.MyFileInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.qjj.studydainty.entity.MyApplication.PATH;


public class ExplorerActivity extends AppCompatActivity {

    private List<MyFileInfo> myFileInfoList = new ArrayList<>();
    private FileInfoAdapter fileInfoAdapter;
    private String inputName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme();
        setContentView(R.layout.activity_explorer);

        RecyclerView recyclerView = findViewById(R.id.recycleView_file);

        myFileInfoList = getDownFile();
        fileInfoAdapter = new FileInfoAdapter(this, myFileInfoList);
        recyclerView.setAdapter(fileInfoAdapter);

        recyclerView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("操作");
                getMenuInflater().inflate(R.menu.file, menu);
            }
        });

        fileInfoAdapter.setOnItemClickListener(new FileInfoAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = getOpenFileIntent(myFileInfoList.get(position).getName());
                if (null == intent) {
                    Toast.makeText(ExplorerActivity.this, "error", Toast.LENGTH_SHORT).show();
                }
                startActivity(intent);
            }

            @Override
            public void OnItemLongClick(View view, int position) {
            }
        });

        //设置布局管理
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //设置动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        //设置分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(this), DividerItemDecoration.VERTICAL));

    }

    private void setTheme() {
        if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_WHITE_THEME_FLAG) {
            setTheme(R.style.DayTheme);
        } else if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_BLACK_THEME_FLAG) {
            setTheme(R.style.NightTheme);
        }
    }

    public Intent getOpenFileIntent(String downloadFileName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File fileDir = new File(PATH);
        if (!fileDir.exists()) {
            boolean b = fileDir.mkdirs();
            if (!b) {
                return null;
            }
        }
        if (downloadFileName == null) {
            return new Intent();
        }
        File file = new File(PATH, downloadFileName);

        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file);
        } else {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(ExplorerActivity.this, getPackageName() + ".provider", file);
        }
        intent.setData(uri);
        return intent;
    }

    public List<MyFileInfo> getDownFile() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

            Uri mImageUri = MediaStore.Downloads.EXTERNAL_CONTENT_URI;
            //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINESE);

            String[] projection = {MediaStore.Images.Media._ID,
                    MediaStore.Downloads.TITLE,
                    MediaStore.Downloads.DISPLAY_NAME,
                    MediaStore.Downloads.DATE_MODIFIED,
                    MediaStore.Downloads.SIZE,
                    MediaStore.Downloads.DATA,
            };

            Cursor mCursor = getContentResolver().query(
                    mImageUri, projection, null, null,
                    null);
            if (mCursor != null) {
                while (mCursor.moveToNext()) {
                     int id = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Downloads._ID));
                    String title = mCursor.getString(mCursor.getColumnIndex(MediaStore.Downloads.TITLE));
                    String name = mCursor.getString(mCursor.getColumnIndex(MediaStore.Downloads.DISPLAY_NAME));
                    long time = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Downloads.DATE_MODIFIED));
                    long sizeLength = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Downloads.SIZE));
                    String url = mCursor.getString(mCursor.getColumnIndex(MediaStore.Downloads.DATA));

                    String size;
                    if (sizeLength > 1048576) {
                        size = sizeLength / 1048576 + "M";
                    } else {
                        size = sizeLength / 1024 + "k";
                    }

                    Bitmap bitmap = null;
                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    try {
                        retriever.setDataSource(url);
                        bitmap = retriever.getPrimaryImage(); //取得指定时间的Bitmap，即可以实现抓图（缩略图）功能
                    } catch (RuntimeException ex) {
                        ex.printStackTrace();
                    } finally {
                        try {
                            retriever.release();
                        } catch (RuntimeException ex) {
                            ex.printStackTrace();
                        }
                    }

                    if (null != bitmap) {
                        bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
                    }

                    MyFileInfo downloadFile = new MyFileInfo(title, size, time,
                            url, bitmap);
                    myFileInfoList.add(downloadFile);
                }
                mCursor.close();
            }
            return myFileInfoList;
        }

        String path = Environment.getExternalStorageDirectory().getPath() + "/DownLoad";
        File dir = new File(path);
        if (!dir.exists()) {
            if (dir.mkdirs()) {
                return null;
            }
        }
        File[] subFile = dir.listFiles();

        if (null == subFile) {
            myFileInfoList.clear();
            return myFileInfoList;
        }
        for (File f : subFile) {
            if (f.isFile()) {
                String size;
                if (f.length() > 1048576) {
                    size = f.length() / 1048576 + "M";
                } else {
                    size = f.length() / 1024 + "k";
                }

                String fileName = f.getName();
                String filePath = f.getPath();
                MyFileInfo downloadFile = new MyFileInfo(fileName, size, f.lastModified(), filePath, getBitmap(fileName, filePath));
                myFileInfoList.add(downloadFile);
            }
        }
        return myFileInfoList;
    }

    private Bitmap getBitmap(String name, String path) {
        Bitmap bitmap = null;
        if (name.length() > 4) {
            //String s = name.substring(name.length() - 3);
            String substring = name.substring(name.length() - 3);
            switch (substring) {
                case "apk":
                    Drawable drawable = getApkThumbnail(ExplorerActivity.this, path);
                    if (drawable != null) {
                        bitmap = drawableToBitmap(drawable);
                    }
                    break;
                case "mp4":
                    //bitmap = ThumbnailUtils.createVideoThumbnail(f.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND);

                    MediaMetadataRetriever media = new MediaMetadataRetriever();
                    media.setDataSource(path);
                    bitmap = media.getFrameAtTime();
                    break;
                case "jpg":
                case "png":
                    bitmap = getImageThumbnail(path);
                    break;
                case "zip": {
                    Resources res = getResources();
                    bitmap = BitmapFactory.decodeResource(res, R.drawable.zip);
                    break;
                }
                case "rar": {
                    Resources res = getResources();
                    bitmap = BitmapFactory.decodeResource(res, R.drawable.rar);
                    break;
                }
            }
        }
        return bitmap;
    }

    /**
     * 根据指定的图像路径和大小来获取缩略图
     * 此方法有两点好处：
     * 1. 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。
     * 2. 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使
     * 用这个工具生成的图像不会被拉伸。
     *
     * @param imagePath 图像的路径
     * @return 生成的缩略图
     */
    private Bitmap getImageThumbnail(String imagePath) {
        Bitmap bitmap;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / 100;
        int beHeight = h / 100;
        int be = Math.min(beWidth, beHeight);
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, 100, 100,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    /**
     * Drawable转Bitmap
     *
     * @param drawable drawable
     * @return bitmap
     */
    public Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        // 取 drawable 的颜色格式

        /*Bitmap.Config config = i != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;*/
        Bitmap.Config config = Bitmap.Config.ARGB_8888;
        //建立对应的Bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);

        return bitmap;
    }

    /**
     * 获取Apk文件的Log图标
     *
     * @param context  上下文
     * @param apk_path Apk路径
     * @return Drawable
     */
    public Drawable getApkThumbnail(Context context, String apk_path) {
        if (context == null) {
            return null;
        }
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageArchiveInfo(apk_path, PackageManager.GET_ACTIVITIES);
            if (null == packageInfo) {
                return null;
            }
            ApplicationInfo appInfo = packageInfo.applicationInfo;
            //获取apk的图标
            appInfo.sourceDir = apk_path;
            appInfo.publicSourceDir = apk_path;
            return appInfo.loadIcon(pm);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int position = fileInfoAdapter.getPosition();
        switch (item.getItemId()) {
            case R.id.open2:
                Intent intent = getOpenFileIntent(myFileInfoList.get(position).getName());
                startActivity(intent);
                break;
            case R.id.update2:
                changeName(position);
                break;
            case R.id.delete2:
                File file = new File(myFileInfoList.get(position).getPath());
                boolean b = file.delete();
                if (b) {
                    Toast.makeText(ExplorerActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ExplorerActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                }
                myFileInfoList.clear();
                myFileInfoList = getDownFile();
                fileInfoAdapter.notifyDataSetChanged();
                break;
            case R.id.delete_all2:
                int success = 0;
                int failed = 0;
                for (MyFileInfo m : myFileInfoList) {
                    file = new File(m.getPath());
                    boolean b1 = file.delete();
                    if (b1) {
                        success++;
                    } else {
                        failed++;
                    }
                }

                Toast.makeText(ExplorerActivity.this, "成功删除" + success + "个文件" + "删除失败" + failed + "个文件", Toast.LENGTH_SHORT).show();

                myFileInfoList.clear();
                myFileInfoList = getDownFile();
                fileInfoAdapter.notifyDataSetChanged();


                break;
            default:
                return false;
        }
        return true;
    }

    private void changeName(final int position) {

        View view = View.inflate(ExplorerActivity.this, R.layout.change_name_dialog, null);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);

        View viewParent = View.inflate(ExplorerActivity.this, R.layout.activity_explorer, null);
        popupWindow.showAtLocation(viewParent, Gravity.CENTER, 0, 0);

        final EditText editTextInputName = view.findViewById(R.id.editText_changename);
        final Button buttonOK = view.findViewById(R.id.button_confirm);
        final Button buttonCancel = view.findViewById(R.id.button_back);

        buttonOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File(myFileInfoList.get(position).getPath());
                String name = file.getName();
                String path = file.getPath();

                inputName = editTextInputName.getText().toString();

                if (inputName.length() <= 0) {
                    Toast.makeText(ExplorerActivity.this, "不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                String str = path.substring(path.lastIndexOf("."));
                //重命名文件
                String s = path.replace(name, inputName + str);
                if (!file.renameTo(new File(s))) {
                    Toast.makeText(ExplorerActivity.this, "error", Toast.LENGTH_SHORT).show();
                }
                popupWindow.dismiss();

                myFileInfoList.clear();
                myFileInfoList = getDownFile();
                fileInfoAdapter.notifyDataSetChanged();
            }
        });
        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });


    }

}
